package com.sunlands.deskmate.utils;

import lombok.extern.slf4j.Slf4j;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.util.Enumeration;

/**
 * @author shixiaopeng
 */
@Slf4j
public class IpUtil {

    /**
     * 获取ip地址，取代配置机器的环境变量
     * 有风险,因为获取的是ip最后一位的个位数
     * @return
     */
    public static long getWorkId() {
        long workId = 0;
        InetAddress ip = null;
        try {
            boolean bFindIP = false;
            Enumeration<NetworkInterface> netInterfaces = (Enumeration<NetworkInterface>) NetworkInterface
                    .getNetworkInterfaces();
            while (netInterfaces.hasMoreElements()) {
                if (bFindIP) {
                    break;
                }
                NetworkInterface ni = (NetworkInterface) netInterfaces
                        .nextElement();

                Enumeration<InetAddress> ips = ni.getInetAddresses();
                while (ips.hasMoreElements()) {
                    ip = (InetAddress) ips.nextElement();
                    if (!ip.isLoopbackAddress()
                            && ip.getHostAddress().matches(
                            "(\\d{1,3}\\.){3}\\d{1,3}")) {
                        bFindIP = true;
                        break;
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (null != ip) {
            String sIP = ip.getHostAddress();
            log.info("ip.getHostAddress() {}", sIP);
            workId = Integer.parseInt(sIP.split("\\.")[3]) % 10;
            if(workId > 7){
                workId = workId/2;
            }
        }
        return workId;
    }

    public static void main(String[] args) {
        log.info(""+getWorkId());
    }
}
